package com.wxx.utils;

import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.*;

@Slf4j
public class IPUtil {

    public static List<String> getIpList() throws Exception {
        InetAddress addr = InetAddress.getLocalHost();
        IPUtil main = new IPUtil();
        return getIpAddr(addr.getHostName());
    }

    private static List<String> getIpAddr(String hostName) throws SocketException, UnknownHostException {
        String osName = System.getProperty("os.name").toLowerCase();
        if (osName.startsWith("window")) {
            return ipv4OrIpv6ByWindow(hostName);
        } else if (osName.startsWith("linux")) {
            return ipv4OrIpv6ByLinux();
        }
        return null;
    }


    private static List<String> ipv4OrIpv6ByLinux() {
        Set<String> set = new HashSet<>();
        try {
            Enumeration<NetworkInterface> networks = NetworkInterface.getNetworkInterfaces();
            while (networks.hasMoreElements()) {
                NetworkInterface network = networks.nextElement();
                // 检查网络接口名称是否匹配
                //if (network.getName().equals("eth0")) { // 替换为你的网卡名称
                Enumeration<InetAddress> addresses = network.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress address = addresses.nextElement();
                    String hostAddress = address.getHostAddress().split("%")[0];
                    set.add(hostAddress);
                }
                //}
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return new ArrayList<>(set);
    }

    private static List<String> ipv4OrIpv6ByWindow(String hostName) throws UnknownHostException {
        List<String> list = new ArrayList<>();
        for (InetAddress it : InetAddress.getAllByName(hostName)) {
            String[] itn = it.toString().split("/");
            String str = itn[1];
            if (str.startsWith("fe80") || str.startsWith("fd00")) {
                continue;
            }
            list.add(str);
        }
        return list;
    }
}